﻿using System;
using System.Diagnostics;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Device.Location;

namespace Agent
{
    public class LocationChangeEventArgs{
        public GeoPosition<GeoCoordinate> Location { get; set; }
    }

    public class LocationServices
    {
        public delegate void PositionChangedEventHandler(object sender, LocationChangeEventArgs e);
        public event PositionChangedEventHandler PositionChanged;

        public void NotifiyPositionChanged(LocationChangeEventArgs e)
        {
            if (null != PositionChanged)
            {
                PositionChanged(this, e);
            }
        }
 
        readonly GeoCoordinateWatcher watcher;
        public LocationServices()
        {
            watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            watcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal
            watcher.StatusChanged += watcher_StatusChanged;
            watcher.PositionChanged += watcher_PositionChanged;
        }

        public void Start()
        {
            watcher.Start();
        }

        public void Stop()
        {
            watcher.Stop();
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            NotifiyPositionChanged(new LocationChangeEventArgs { Location = e.Position });
        }

      
        public GeoPosition<GeoCoordinate> GeCurrentLocation()
        {
            return watcher.Position;
        }

        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    if (watcher.Permission == GeoPositionPermission.Denied)
                    {
                        Debug.WriteLine("you have this application access to location.");
                    }
                    else
                    {
                        Debug.WriteLine("location is not functioning on this device");
                    }
                    break;

                case GeoPositionStatus.Initializing:
                    //startLocationButton.IsEnabled = false;
                    break;

                case GeoPositionStatus.NoData:
                    Debug.WriteLine("location data is not available.");
                    break;

                case GeoPositionStatus.Ready:
                    Debug.WriteLine("location data is available.");
                    break;
            }
        }
    }
}
